import os, md5
from model import Node, connection
from timestamp import Timestamp

BLOCK_SIZE = os.stat('.').st_blksize

def register(file, timestamp, setid):
    file_dirname = os.path.relpath(os.path.dirname(file))
    file_basename = os.path.basename(file)

    with open(file, 'r') as f: d = f.read(BLOCK_SIZE)
    digest = md5.new(d).hexdigest()
    # with unique index 
    node = connection.Node.one({'path':str(file_dirname), 'filename':str(file_basename), 'setid':str(setid), 'md5':digest})
    if node is None: # NEW
        print "C: ", file
        node = connection.Node()
        node.setid = setid.decode('utf-8')
        node.path = file_dirname.decode('utf-8')
        node.filename = file_basename.decode('utf-8')
        node.is_symlink = os.path.islink(file)
        node.date_updated = Timestamp.utcdatetime_from(timestamp)
        node.timestamp = timestamp
        node.md5 = digest

    else: # EXIST
        print "U: ", file
        node.is_symlink = os.path.islink(file)
        node.date_updated = Timestamp.utcdatetime_from(timestamp)

    node.save()

if __name__ == '__main__':
    pass
